//
//  UIBarButtonItem+AG.swift
//  ASW
//
//  Created by zhuxuhong on 2020/11/22.
//

import UIKit
import BWToolKit

extension UIBarButtonItem {
    struct EventASKey {
        static var tapped = "tapped"
    }
    
    public static func custom(
        view: UIView,
        width: CGFloat,
        height: CGFloat
    ) -> UIBarButtonItem {
        let wrapper = UIView(frame: .init(origin: .zero, size: .init(width: width, height: height)))
        view.frame = wrapper.bounds
        wrapper.addSubview(view)
        return UIBarButtonItem(customView: wrapper)
    }
    
    public static func system(
        title: String? = nil,
        image: UIImage? = nil,
        handler: BlockVoid? = nil
    ) -> UIBarButtonItem?
    {
        var item: UIBarButtonItem?
        if let title = title {
            item = UIBarButtonItem(title: title, style: .plain, target: nil, action: nil)
            let attr = [
                NSAttributedString.Key.font: UIFont.system17.semiBold,
                NSAttributedString.Key.foregroundColor: UIColor.black
            ]
            item?.setTitleTextAttributes(attr, for: .normal)
            item?.setTitleTextAttributes(attr, for: .highlighted)
            item?.setTitleTextAttributes([
                NSAttributedString.Key.font: UIFont.system17.semiBold,
                NSAttributedString.Key.foregroundColor: UIColor.black.a2
            ], for: .disabled)
        }
        else if let image = image {
            item = UIBarButtonItem(image: image, style: .plain, target: nil, action: nil)
        }
        
        if let item = item, let handler = handler {
            item.bw_addTargetForAction(item, action: #selector(_tapped))
            Objcer.setASValue(handler, for: item, key: &EventASKey.tapped, policy: .copy)
        }
        
        return item
    }
    
    public func bw_addTargetForAction(_ target: AnyObject, action: Selector) {
        self.target = target
        self.action = action
    }
    
    @objc private func _tapped(){
        if let handler = Objcer.getASValue(for: self, key: &EventASKey.tapped) as? BlockVoid {
            handler()
        }
    }
}
